#include <bits/stdc++.h>

using namespace std;
template<typename T=int>
inline T read() {
    T x;
    cin >> x;
    return x;
}

int main() {
    int n(read<int>()), q(read<int>());
    vector<stack<int>> A(n, stack<int>());
    while (q--) {
        int op(read<int>());
        if (op == 0) {
            int t = read<int>(), e = read<int>();
            A[t].push(e);
        } else if (op == 1) {
            int t = read<int>();
            if (not A[t].empty())cout << A[t].top() << endl;
        } else if (op == 2) {
            int t = read<int>();
            if (not A[t].empty())A[t].pop();
        }

    }
    return 0;
}